package com.vbobot.demo.spring.cloud.gateway.gateway.server.filter.global;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Bobo
 * @date 2022/10/26
 */
@Slf4j
@Component
public class LimitGlobalFilter implements GlobalFilter {

    @Resource RedissonClient redissonClient;
    RRateLimiter rateLimiter;

    @PostConstruct
    public void init() {
        rateLimiter = redissonClient.getRateLimiter("bobo:test:rateLimiter");
        rateLimiter.trySetRate(RateType.OVERALL, 10000, 1, RateIntervalUnit.SECONDS);
        log.info("init rate limiter");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if (rateLimiter.tryAcquire()) {
            return chain.filter(exchange);
        } else {
            final ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
            return response.setComplete();
        }
    }
}
